import PmTargetEnactDrawer from '@/components/drawer/pmTargetEnactDrawer'
import TargetLibImportDrawer from '@/components/drawer/targetLibImportDrawer'
import {IconImg} from '@/components/image'
import {CnMediumP, CnMediumSpan, CnNormalP, CnNormalSpan} from '@/components/text'
import deepClone from '@/libs/deepClone'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {unReplaceBreak} from '@/libs/toolkit'
import {PropType, reactive, toRefs, ref, defineComponent, watch, computed, onMounted} from 'vue'
const {message} = ant_design_vue

export const DimensionTypeSelect = defineComponent({
  name: 'DimensionTypeSelect',
  emits: {
    indexClick: (data: PmGroupDimensionTypeCode): boolean => true
  },
  setup(props, {emit}) {
    return () => (
      <div class='flex flex-col items-center justify-center gap-y-32'>
        <CnNormalP>请根据需要考核的指标内容，点击添加对应的考核维度</CnNormalP>
        <div class='flex items-center gap-x-32'>
          <div
            class='cursor-pointer'
            onClick={() => {
              emit('indexClick', '0020')
            }}
          >
            <IconImg imgName='kpi' class='w-50 h-50 mb-12'></IconImg>
            <CnMediumP>量化指标</CnMediumP>
          </div>

          <div
            class='cursor-pointer'
            onClick={() => {
              emit('indexClick', '0021')
            }}
          >
            <IconImg imgName='fix-kpi' class='w-50 h-50 mb-12'></IconImg>
            <CnMediumP>定性指标</CnMediumP>
          </div>
        </div>
      </div>
    )
  }
})

/**考核维度 单维度面板 */
export const DimensionDashboard = defineComponent({
  props: {
    pmGroupDimension: {
      type: Object as PropType<Evaluation.PmGroupDimension>,
      required: true
    }
  },
  emits: {
    edit: (): boolean => true,
    delete: (): boolean => true
  },
  setup(props, {emit, slots}) {
    return () => (
      <div class='dimensionDashboard border-1 border-infoLight rounded-4 pt-60 px-16 py-10 relative overflow-hidden mb-24'>
        <div
          class='dimensionDashboard-header absolute top-0 left-0 w-full px-16 pt-16'
          style={{
            background: 'linear-gradient(to bottom,#ecf5ff 0%,#fff 100%)'
          }}
        >
          {/* 维度内容主标题 */}
          <div class='header-title w-full flex items-center justify-between'>
            {/* 主标题文本 */}
            <div class='w-full flex items-center'>
              {/* 伸缩箭头 */}
              <i class='iconfont icon-xiajiantou-triangle text-info text-12 transform scale-75'></i>
              {/* 文本 */}
              <CnMediumSpan class='text-16 ml-8'>
                {props.pmGroupDimension.pmGroupDimensionName}（
                {props.pmGroupDimension.pmGroupDimensionWeight || 0}
                %）
              </CnMediumSpan>
            </div>
            {/* 主标题右侧功能按钮 */}
            <div class='flex items-center gap-x-12'>
              <a-button
                class='h-auto rounded-4 px-8'
                onClick={() => {
                  emit('edit')
                }}
              >
                <i class='iconfont icon-xiugai text-14'></i>
              </a-button>
              <a-button
                class='h-auto rounded-4 px-8'
                onClick={() => {
                  emit('delete')
                }}
              >
                <i class='iconfont icon-shanchu text-12'></i>
              </a-button>
            </div>
          </div>
          {/* 维度内容副标题 */}
          <div class='header-subTitle w-full pl-20'>
            <CnNormalSpan class='text-12'>
              {props.pmGroupDimension.pmGroupDimensionTypeCode === '0020'
                ? '量化指标'
                : props.pmGroupDimension.pmGroupDimensionTypeCode === '0021'
                ? '定性指标'
                : '指标类型错误'}
            </CnNormalSpan>

            {props.pmGroupDimension.isImport
              ? [
                  <CnNormalSpan class='text-infoHalf text-12 mx-8'>|</CnNormalSpan>,
                  <CnNormalSpan class='text-12'>制定目标时可导入</CnNormalSpan>
                ]
              : ''}
            {props.pmGroupDimension.isCustomSelf
              ? [
                  <CnNormalSpan class='text-infoHalf text-12 mx-8'>|</CnNormalSpan>,
                  <CnNormalSpan class='text-12'>制定目标时可新增</CnNormalSpan>
                ]
              : ''}
          </div>
        </div>
        {slots.default?.()}
      </div>
    )
  }
})

/**考核维度 单维度面板-维度内容 */
export const DimensionTargetContent = defineComponent({
  props: {
    pmGroupDimensionTargetList: {
      type: Array as PropType<Evaluation.PmGroupDimensionTarget[]>,
      default: []
    },
    pmGroupDimension: {
      type: Object as PropType<Evaluation.PmGroupDimension>,
      required: true
    },
    dimensIndex: {
      type: Number,
      required: true
    },
    showAppointScore: {
      type: Boolean,
      default: true
    }
  },
  emits: {
    'update:pmGroupDimensionTargetList': (
      data: Evaluation.PmGroupDimensionTarget[],
      idx: number
    ): boolean => true
  },
  setup(props, {emit}) {
    let state = reactive<{
      addTargetDrawerVisible: boolean
      editTargetDrawerVisible: boolean
      editTargetDrawerData: Evaluation.PmGroupDimensionTarget | undefined
      targetLibImportDrawerVisible: boolean
      dimensIndex: number
      pmGroupDimensionTargetList: Evaluation.PmGroupDimensionTarget[]
    }>({
      addTargetDrawerVisible: false,
      editTargetDrawerVisible: false,
      editTargetDrawerData: undefined,
      targetLibImportDrawerVisible: false,
      dimensIndex: -1,
      pmGroupDimensionTargetList: []
    })

    /**最大权重 */
    const maxTargetWeightCount = computed(() => props.pmGroupDimension.pmGroupDimensionWeight)

    /**所有已有指标的总权重 */
    const targetWeightCount = computed(
      () =>
        eval(
          state.pmGroupDimensionTargetList.map(item => item.pmGroupDimensionTargetWeight).join('+')
        ) || 0
    )

    /**表格头 */
    const columns = computed<CColumn<Evaluation.PmGroupDimensionTarget>[]>(() => {
      let targetNum = props.pmGroupDimensionTargetList.length
      let targetWeightList = props.pmGroupDimensionTargetList.map(item => {
        return Number(
          typeof item.pmGroupDimensionTargetWeight === 'number'
            ? item.pmGroupDimensionTargetWeight
            : Number(item.pmGroupDimensionTargetWeight)
        )
      })
      let targetWeightCount = 0

      for (let i = 0; i < targetWeightList.length; i++) {
        targetWeightCount += targetWeightList[i] || 0
      }

      return [
        {
          title: `指标名称（${targetNum}）`,
          dataIndex: 'pmGroupDimensionTargetName',
          ellipsis: true,
          width: 240
        },
        {
          title: `权重（${targetWeightCount}）%`,
          dataIndex: 'pmGroupDimensionTargetWeight',
          ellipsis: true,
          width: 160
        },
        {
          title: '考核标准',
          dataIndex: 'pmGroupDimensionTargetStand',
          ellipsis: true
        },
        {
          title: '自评模板',
          dataIndex: 'selfContentTem',
          ellipsis: true
        },
        {
          title: '备注',
          dataIndex: 'pmGroupDimensionTargetDesc',
          ellipsis: true,
          width: 200
        },
        {
          title: '操作',
          dataIndex: 'utils',
          width: 160
        }
      ]
    })

    onMounted(() => {
      // pmGroupDimensionSelfContentTem
      props
    })

    watch(
      () => props.pmGroupDimensionTargetList,
      n => {
        console.log('接收到的指标列表', n)
        // state.pmGroupDimensionTargetList = n
        n.forEach(target => {
          target.selfContentTem = target.pmGroupDimensionSelfContentTem
            ? target.pmGroupDimensionSelfContentTem
            : ''
        })
        state.pmGroupDimensionTargetList = n
      },
      {immediate: true}
    )

    watch(
      () => state.pmGroupDimensionTargetList,
      n => {
        n.forEach(target => {
          target.pmGroupDimensionSelfContentTem = target.selfContentTem ? target.selfContentTem : ''
        })
        state.pmGroupDimensionTargetList = n
        console.log('指标列表变化11c', n)
        pmGroupDimensionTargetListSort()
      },
      {deep: true}
    )

    function pmGroupDimensionTargetListSort() {
      console.log('指标列表排序')
      for (let i = 0; i < state.pmGroupDimensionTargetList.length; i++) {
        if (state.pmGroupDimensionTargetList[i].sort !== i) {
          state.pmGroupDimensionTargetList[i].sort = i
        }
      }
      console.log()
      console.log('指标列表变化11cc', state.pmGroupDimensionTargetList)

      emit('update:pmGroupDimensionTargetList', state.pmGroupDimensionTargetList, props.dimensIndex)
    }

    /**添加指标 */
    function addPmGroupDimensionTarget(data: Evaluation.PmGroupDimensionTarget) {
      console.log('添加指标', data)
      const flag = checkWeightIsOverproof(data.pmGroupDimensionTargetWeight, 'add')
      if (!flag) return
      data.sort = state.pmGroupDimensionTargetList.length
      state.pmGroupDimensionTargetList.push(data)
    }

    /**修改指标 */
    function editPmGroupDimensionTarget(data: Evaluation.PmGroupDimensionTarget) {
      console.log('修改指标', data)
      const currentTargetIdx = state.pmGroupDimensionTargetList.findIndex(
        item => item.sort === data.sort
      )
      const currentTarget = state.pmGroupDimensionTargetList[currentTargetIdx]
      const flag = checkWeightIsOverproof(
        data.pmGroupDimensionTargetWeight - currentTarget.pmGroupDimensionTargetWeight,
        'edit'
      )
      if (!flag) return
      state.pmGroupDimensionTargetList.splice(currentTargetIdx, 1, data)
    }

    function handleTableEditClick(data: Evaluation.PmGroupDimensionTarget) {
      state.editTargetDrawerData = deepClone(data)
      state.editTargetDrawerVisible = true
    }

    function handleTableDeleteClick(targetIdx: number) {
      state.pmGroupDimensionTargetList.splice(targetIdx, 1)
    }

    function handleTargetLibImportClick() {
      state.targetLibImportDrawerVisible = true
    }

    function handleTargetLibImportConfirm(data: Evaluation.PmGroupDimensionTarget[]) {
      data.forEach(item => {
        addPmGroupDimensionTarget(item)
      })
    }

    function checkWeightIsOverproof(newWeight: number, type: 'add' | 'edit' = 'add') {
      switch (type) {
        case 'add':
          if (maxTargetWeightCount.value === undefined) {
            message.warning(`有指标未指定权重`)
            return false
          } else if (targetWeightCount.value + newWeight > maxTargetWeightCount.value) {
            const diffCount = maxTargetWeightCount.value - targetWeightCount.value

            if (diffCount > 0 || diffCount < 0) {
              message.warning({
                content: `指标的权重仅剩余${diffCount}`
              })
            } else {
              message.warning(`指标权重的总和已达到${targetWeightCount.value}`)
            }

            return false
          }

          return true
        case 'edit':
          if (maxTargetWeightCount.value === undefined) {
            message.warning(`有指标未指定权重`)
            return false
          } else if (targetWeightCount.value + newWeight > maxTargetWeightCount.value) {
            message.warning('修改指标时，权重超出最大范围')
            return false
          }
          return true
      }
    }

    return () => (
      <div class='mt-32'>
        {props.pmGroupDimensionTargetList.length ? (
          <a-table
            class='custom-table'
            pagination={false}
            columns={columns.value}
            data-source={state.pmGroupDimensionTargetList}
            bordered
            v-slots={{
              bodyCell: ({
                text,
                column,
                record,
                index
              }: CBodyCell<Evaluation.PmGroupDimensionTarget>) => {
                switch (column.dataIndex) {
                  case 'utils':
                    return (
                      <div class='p-16 flex items-center gap-x-16'>
                        <CnNormalSpan
                          class='text-primary cursor-pointer text-12'
                          onClick={() => {
                            handleTableEditClick(record)
                          }}
                        >
                          编辑
                        </CnNormalSpan>
                        <CnNormalSpan
                          class='text-primary cursor-pointer text-12'
                          onClick={() => {
                            handleTableDeleteClick(index)
                          }}
                        >
                          删除
                        </CnNormalSpan>
                      </div>
                    )
                  case 'pmGroupDimensionTargetWeight ':
                    return (
                      <div class='p-16'>
                        <i class='text-18 text-black font-bold'>{text}</i>
                        <span class='text-18 text-black font-bold'>%</span>
                      </div>
                    )
                  case 'pmGroupDimensionTargetName':
                    return (
                      <CnNormalP
                        class='p-16 text-12'
                        onDblclick={() => {
                          handleTableEditClick(record)
                        }}
                      >
                        {text}
                        <CnNormalSpan class='text-danger'>
                          {record.isMustSelect === 1 ? '（必选）' : ''}
                        </CnNormalSpan>
                      </CnNormalP>
                    )

                  case 'selfContentTem':
                    return (
                      <CnNormalP
                        class='p-16 text-12'
                        onDblclick={() => {
                          handleTableEditClick(record)
                        }}
                      >
                        {text ? text : ''}
                      </CnNormalP>
                    )
                  default:
                    return (
                      <CnNormalP
                        class='p-16 text-12'
                        style={{
                          whiteSpace: 'break-spaces'
                        }}
                        onDblclick={() => {
                          handleTableEditClick(record)
                        }}
                      >
                        {unReplaceBreak(text + '')}
                      </CnNormalP>
                    )
                }
              }
            }}
          ></a-table>
        ) : null}

        <div class='flex items-center gap-x-8 mt-16'>
          <a-button
            type='primary'
            class='rounded-4 bg-primary text-white'
            onClick={handleTargetLibImportClick}
          >
            <CnMediumSpan class='text-white'>
              <i class='iconfont icon-daoru text-12 mr-8 text-white'></i>
              指标库导入
            </CnMediumSpan>
          </a-button>
          <a-button
            type='primary'
            class='rounded-4 bg-primary text-white'
            onClick={() => {
              state.addTargetDrawerVisible = true
            }}
          >
            <CnMediumSpan class='text-white'>
              <i class='iconfont icon-xiaojiahao text-16 text-white'></i>
              增加指标项
            </CnMediumSpan>
          </a-button>
        </div>
        <PmTargetEnactDrawer
          title='添加指标'
          v-model={[state.addTargetDrawerVisible, 'visible']}
          onConfirm={addPmGroupDimensionTarget}
          showAppointScore={props.showAppointScore}
        ></PmTargetEnactDrawer>

        <PmTargetEnactDrawer
          title='修改指标'
          type='edit'
          v-model={[state.editTargetDrawerVisible, 'visible']}
          defaultPmGroupDimensionTarget={state.editTargetDrawerData}
          onConfirm={editPmGroupDimensionTarget}
          showAppointScore={props.showAppointScore}
        ></PmTargetEnactDrawer>

        <TargetLibImportDrawer
          v-model={[state.targetLibImportDrawerVisible, 'visible']}
          onConfirm={handleTargetLibImportConfirm}
        ></TargetLibImportDrawer>
      </div>
    )
  }
})
